<!-- 创建时间: 2020年12月23日 星期三 10:21 -->
<template>
    <div class="coursesClass_container">
        <el-divider content-position="left">考试课程</el-divider>
        <el-row class="class_row" :gutter="10">
            <center>
                <span v-show="listData.length == 0" style="color: darkgray;"
                    >暂无创建考试</span
                >
            </center>
            <el-col
                :xs="24"
                :sm="24"
                :md="10"
                :lg="6"
                v-for="(item, index) in listData"
                :key="index"
            >
                <el-card class="box-card">
                    <el-button
                        class="editBtn"
                        v-if="isShowEditExamination(item, index)"
                        @click="addExaminationQuestions(item)"
                        type="primary"
                        icon="el-icon-edit"
                        circle
                    ></el-button>
                    <el-tooltip
                        v-if="!isShowEditExamination(item, index)"
                        class="editBtn"
                        effect="dark"
                        content="查看试题"
                        placement="top"
                    >
                        <el-button
                            v-if="!isShowEditExamination(item, index)"
                            icon="el-icon-view"
                            circle
                            @click="viewPreview(item)"
                        ></el-button>
                    </el-tooltip>
                    <el-row class="box-card_elrow">
                        <el-col class="box-card_elrow_elcol" :md="12" :sm="24" :xs="24">
                            <div>
                                <el-tag type="info">考试班级:</el-tag>
                                <el-tag>{{ item.className }}</el-tag>
                            </div>
                            <div>
                                <el-tag type="info">考试课程:</el-tag>
                                <el-tag>{{ item.coursesName }}</el-tag>
                            </div>
                            <div>
                                <el-tag type="info">班级人数:</el-tag>
                                <el-tag>{{ item.classPeopleNumber }}</el-tag>
                            </div>
                            <div>
                                <el-tag type="info">试题库号:</el-tag>
                                <el-tag
                                    :type="
                                        item.questionBank == null
                                            ? 'danger'
                                            : ''
                                    "
                                    >{{
                                        item.questionBank == null
                                            ? "未添加试题"
                                            : item.questionBank
                                    }}</el-tag
                                >
                            </div>
                            <div>
                                <el-tag type="info">开始时间:</el-tag>
                                <el-tag>{{ item.startTime }}</el-tag>
                            </div>
                            <div>
                                <el-tag type="info">结束时间:</el-tag>
                                <el-tag>{{ item.endTime }}</el-tag>
                                <div class="block" v-show="item.isEdit">
                                    <el-date-picker
                                        v-model="updateStartEndTime"
                                        type="datetimerange"
                                        align="right"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                    >
                                    </el-date-picker>
                                </div>
                            </div>
                        </el-col>
                        <el-col class="box-card_elrow_elcol" :md="12" :sm="24" :xs="24">
                            <!-- 考试结束 -->
                            <el-image
                            v-if="isShowStudentResult(item, index)"
                            src="images/complete.png"
                            fit="fill"></el-image>
                            <!-- 考试中 -->
                            <el-image
                            v-if="!isShowStudentResult(item, index) && !isShowEditExamination(item, index)"
                            src="images/inexam.png"
                            fit="fill"></el-image>
                            <el-image
                            v-if="!isShowStudentResult(item, index) && isShowEditExamination(item, index)"
                            src="images/waitexam.png"
                            fit="fill"></el-image>
                        </el-col>
                    </el-row>

                    <el-popconfirm
                        :title="
                            '你确定要删除【' +
                                item.coursesName +
                                '】考试记录吗？'
                        "
                        @confirm="deleteExamination(item)"
                    >
                        <el-link type="info" slot="reference">删除考试</el-link>
                    </el-popconfirm>
                    <el-link
                        type="info"
                        v-if="isShowEditExamination(item)"
                        @click.prevent="editExamination(item, index)"
                        >{{ item.isEdit ? "取消编辑" : "编辑考试" }}</el-link
                    >
                    <el-link
                        type="info"
                        v-show="item.isEdit"
                        @click.prevent="saveExamination(item, index)"
                        >保存编辑</el-link
                    >
                    <el-link
                        type="success"
                        v-if="isShowStudentResult(item, index)"
                        @click.prevent="checkStudentResult(item)"
                        >考试成绩</el-link
                    >
                    <el-tooltip
                        :content="
                            '考试结束学生查看试题分析权限: ' +
                                (item.studentPreview ? '关闭' : '开启')
                        "
                        placement="top"
                    >
                        <el-switch
                            v-model="item.studentPreview"
                            active-color="#13ce66"
                            inactive-color="#dcdcdc"
                            @change="upStudentPreview(item)"
                        >
                        </el-switch>
                    </el-tooltip>
                </el-card>
            </el-col>
        </el-row>
        <el-button
            plain
            @click="openInfoTips"
            style="display: none"
        ></el-button>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
        //这里存放数据
        return {
            listData: [], // 列表数据
            updateStartEndTime: [], // 更新的开始结束时间
            questionsList: [], // 试题库列表
            flag: JSON.parse(sessionStorage.getItem("flag")), // 是否用户为初始密码状态
        };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        // 是否显示 编辑考试时间
        isShowEditExamination(item) {
            if (new Date(item.startTime).getTime() < new Date().getTime()) {
                return false;
            }
            return true;
        },
        // 是否显示 查看成绩
        isShowStudentResult(item) {
            if (
                new Date(
                    new Date(item.endTime).setMinutes(
                        new Date(item.endTime).getMinutes() + 5
                    )
                ).getTime() < new Date().getTime()
            ) {
                return true;
            }
            return false;
        },
        // 更新学生试题分析查看权限
        upStudentPreview(item) {
            this.$http
                .post("upStudentPreview", {
                    id: item.id,
                    questionBank: item.questionBank,
                    status: item.studentPreview,
                })
                .then((res) => {
                    if (res.body) {
                        let message =
                            "学生试题分析权限 <b style='color:green;'>" +
                            (item.studentPreview ? "开启" : "关闭") +
                            "</b> 成功";
                        this.openInfoTips(
                            item.className,
                            message,
                            "success",
                            3000
                        );
                    } else {
                        let message =
                            "学生试题分析权限 <b style='color:red;'>" +
                            (item.studentPreview ? "开启" : "关闭") +
                            "</b> 失败";
                        this.openInfoTips(
                            item.className,
                            message,
                            "error",
                            3000
                        );
                    }
                })
                .catch((err) => {
                    this.openInfoTips(
                        "失败",
                        "系统出错啦,请稍后重试",
                        "error",
                        3000
                    );
                });
        },
        // 查看预览
        viewPreview(item) {
            this.$store.commit("setAddQuestions", item);
            this.$http
                .post("autoGetQuestionBankInfo", {
                    questionBankName: item.questionBank,
                })
                .then((res) => {
                    let str = JSON.parse(res.bodyText);
                    for (let i = 0; i < str.length; i++) {
                        str[i].optionList = str[i].optionList.split("&");
                        if (str[i].type != "radio") {
                            str[i].rightOption = str[i].rightOption.split("&");
                        }
                    }
                    this.$store.commit("setQuestionsList", str);
                    let openViewPage = this.$router.resolve({
                        path: "/viewPreview",
                    });
                    window.open(openViewPage.href, "_blank");
                });
        },
        // 查看所选择班级的课程考试成绩情况
        checkStudentResult(item) {
            /**
             * className: "软件工程2020级专升本1班"
                classNumber: "2006831"
                classPeopleNumber: 1
                coursesName: "Java"
             */
            let obj = {
                className: item.className,
                classNumber: item.classNumber,
                classPeopleNumber: item.classPeopleNumber,
                coursesName: item.coursesName,
                questionBank: item.questionBank,
            };
            this.$router.push({
                name: "checkStudentResult",
                params: { data: JSON.stringify(obj) },
            });
        },
        // 自动获取考试记录
        autoGetExaminationRecord() {
            if (!this.flag) return;
            this.$http
                .get(
                    "autoGetExaminationRecord?teacherNumber=" +
                        this.$store.getters.getUserNumber
                )
                .then((res) => {
                    for (let i = 0; i < res.body.length; i++) {
                        this.$set(res.body[i], "isEdit", false);
                    }
                    this.listData = res.body;
                });
        },
        // 删除考试 根据教师姓名、班级号、课程
        deleteExamination(item) {
            if (
                new Date(item.startTime).getTime() < new Date().getTime() &&
                new Date(item.endTime).getTime() > new Date().getTime()
            ) {
                this.$message.error("考试进行中...请结束后重试");
                return;
            }
            let data = {
                teacherNumber: this.$store.getters.getUserNumber,
                classNumber: item.classNumber,
                coursesName: item.coursesName,
                questionBank: item.questionBank,
            };
            this.$http
                .post("deleteExamination", { data: JSON.stringify(data) })
                .then((res) => {
                    if (res.body == 1) {
                        this.openInfoTips(
                            "成功",
                            "课程考试 " + item.coursesName + " 删除成功",
                            "success",
                            3000
                        );
                        this.autoGetExaminationRecord();
                    } else {
                        this.openInfoTips(
                            "失败",
                            "课程考试 " +
                                item.coursesName +
                                " 删除失败。" +
                                res.body,
                            "success",
                            0
                        );
                    }
                });
        },
        // 编辑考试
        editExamination(item, index) {
            this.listData[index].isEdit = !this.listData[index].isEdit;
            this.updateStartEndTime = [item.startTime, item.endTime];
        },
        saveExamination(item, index) {
            let startTime = this.dateFormat(
                "yyyy-mm-dd HH:MM",
                this.updateStartEndTime[0]
            );
            let endTime = this.dateFormat(
                "yyyy-mm-dd HH:MM",
                this.updateStartEndTime[1]
            );
            let data = {
                teacherNumber: this.$store.getters.getUserNumber,
                classNumber: item.classNumber,
                coursesName: item.coursesName,
                startTime: startTime,
                endTime: endTime,
            };
            this.listData[index].startTime = startTime;
            this.listData[index].endTime = endTime;
            this.$http
                .post("editExamination", { data: JSON.stringify(data) })
                .then((res) => {
                    if (res.body == 1) {
                        this.listData[index].isEdit = !this.listData[index]
                            .isEdit;
                        this.openInfoTips(
                            "成功",
                            item.className +
                                " " +
                                item.coursesName +
                                "课程考试时间修改成功",
                            "success",
                            6000
                        );
                    } else {
                        this.openInfoTips(
                            "失败",
                            item.className +
                                " " +
                                item.coursesName +
                                "课程考试时间修改失败。" +
                                res.body,
                            "error",
                            0
                        );
                    }
                });
        },
        // 日期时间格式化
        dateFormat(fmt, date) {
            let ret;
            const opt = {
                "y+": date.getFullYear().toString(), // 年
                "m+": (date.getMonth() + 1).toString(), // 月
                "d+": date.getDate().toString(), // 日
                "H+": date.getHours().toString(), // 时
                "M+": date.getMinutes().toString(), // 分
                "S+": date.getSeconds().toString(), // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
            };
            for (let k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                    fmt = fmt.replace(
                        ret[1],
                        ret[1].length == 1
                            ? opt[k]
                            : opt[k].padStart(ret[1].length, "0")
                    );
                }
            }
            return fmt;
        },
        // 添加考题
        addExaminationQuestions(item) {
            this.$store.commit("setAddQuestions", item);
            this.$router.push({
                path: "/addExaminationQuestions",
                query: { form: this.$route.path },
            });
        },
        openInfoTips(title, message, type, duration) {
            this.$notify({
                title: title,
                message: message,
                type: type,
                duration: duration,
                dangerouslyUseHTMLString: true,
            });
        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.autoGetExaminationRecord();
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    //当data中定义的数据有变化时就会加载updated方法
    updated() {},
};
</script>

<style lang="scss" scoped>
//@import url(); 引入公共css类
.coursesClass_container {
    .class_row {
        margin-top: 13px;
        padding: 10px;
        .box-card {
            height: auto;
            margin-bottom: 13px;
            position: relative;
            user-select: none;

            .editBtn {
                position: absolute;
                right: 10px;
                top: 10px;
                z-index: 1;
            }
            .box-card_elrow{
                display: flex; 
                align-items: center;
                .box-card_elrow_elcol > div{
                    span{
                        margin-bottom: 10px;
                    }
                    span:nth-child(2){
                        width: 15em;
                    }
                }
            }
        }
        .box-card:hover {
            border: 1px solid sandybrown;
        }
    }
}
</style>
